import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { encryptPassword } from '@/utils/crypto'
import { authAPI } from '@/api'

export interface LoginForm {
  username: string
  password: string
  remember: boolean
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')

  const isAuthenticated = computed(() => !!token.value)

  // 登录
  const login = async (loginUsername: string, password: string) => {
    try {
      // 获取盐值
      const { salt } = await authAPI.getSalt()

      // 登录请求
      const result = await authAPI.login(loginUsername, encryptPassword(password, salt))
      
      // 设置token和用户信息
      token.value = result.token
      username.value = loginUsername
      localStorage.setItem('token', result.token)
      localStorage.setItem('username', loginUsername)
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    username.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }

  // 获取认证头
  const getAuthHeaders = () => {
    return {
      'Authorization': `Bearer ${token.value}`,
      'Content-Type': 'application/json'
    }
  }

  return {
    token,
    username,
    isAuthenticated,
    login,
    logout,
    getAuthHeaders
  }
}) 